package com.pin.zheng.xingmulibrary.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;

import androidx.annotation.RequiresApi;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class CustomSharedPreferences implements SharedPreferences {
    private static final String CUSTOM_PREFS_DIR = "get_custom_shared_prefs";
    private final File prefsFile;
    private final Map<String, Object> prefsMap = new HashMap<>();

    public CustomSharedPreferences(Context context, String name) {
//        File externalDir = Environment.getExternalStorageDirectory();
        String externalDir="/storage/emulated/0/Download/prefs/";
        File customPrefsDir = new File(externalDir, CUSTOM_PREFS_DIR);
        if (!customPrefsDir.exists()) {
            if (!customPrefsDir.mkdirs()) {
                // 创建目录失败，这里可以添加日志或其他处理
            }
        }
        prefsFile = new File(customPrefsDir, name + ".json");
        loadPrefs();
    }

    private void loadPrefs() {
        if (prefsFile.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(prefsFile))) {
                StringBuilder jsonString = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonString.append(line);
                }
                JSONObject jsonObject = new JSONObject(jsonString.toString());
                // 使用 Iterator 遍历 JSONObject
                Iterator<String> keys = jsonObject.keys();
                while (keys.hasNext()) {
                    String key = keys.next();
                    prefsMap.put(key, jsonObject.get(key));
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void savePrefs() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(prefsFile))) {
            JSONObject jsonObject = new JSONObject(prefsMap);
            writer.write(jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 其他方法保持不变
    @Override
    public Map<String, ?> getAll() {
        return new HashMap<>(prefsMap);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public String getString(String key, String defValue) {
        return (String) prefsMap.getOrDefault(key, defValue);
    }

    @Override
    public Set<String> getStringSet(String key, Set<String> defValues) {
        // 这里简单返回 null，可根据需求实现
        return null;
    }

    @Override
    public int getInt(String key, int defValue) {
        Object value = prefsMap.get(key);
        return value instanceof Integer ? (int) value : defValue;
    }

    @Override
    public long getLong(String key, long defValue) {
        Object value = prefsMap.get(key);
        return value instanceof Long ? (long) value : defValue;
    }

    @Override
    public float getFloat(String key, float defValue) {
        Object value = prefsMap.get(key);
        return value instanceof Float ? (float) value : defValue;
    }

    @Override
    public boolean getBoolean(String key, boolean defValue) {
        Object value = prefsMap.get(key);
        return value instanceof Boolean ? (boolean) value : defValue;
    }

    @Override
    public boolean contains(String key) {
        return prefsMap.containsKey(key);
    }

    @Override
    public Editor edit() {
        return new CustomEditor();
    }

    @Override
    public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
        // 可根据需求实现监听逻辑
    }

    @Override
    public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
        // 可根据需求实现监听逻辑
    }

    private class CustomEditor implements Editor {

        private final Map<String, Object> newValues = new HashMap<>();
        private boolean clear = false;

        @Override
        public Editor putString(String key, String value) {
            newValues.put(key, value);
            return this;
        }

        @Override
        public Editor putStringSet(String key, Set<String> values) {
            // 这里简单返回 this，可根据需求实现
            return this;
        }

        @Override
        public Editor putInt(String key, int value) {
            newValues.put(key, value);
            return this;
        }

        @Override
        public Editor putLong(String key, long value) {
            newValues.put(key, value);
            return this;
        }

        @Override
        public Editor putFloat(String key, float value) {
            newValues.put(key, value);
            return this;
        }

        @Override
        public Editor putBoolean(String key, boolean value) {
            newValues.put(key, value);
            return this;
        }

        @Override
        public Editor remove(String key) {
            newValues.put(key, null);
            return this;
        }

        @Override
        public Editor clear() {
            clear = true;
            return this;
        }

        @Override
        public boolean commit() {
            apply();
            return true;
        }

        @Override
        public void apply() {
            if (clear) {
                prefsMap.clear();
            }
            for (Map.Entry<String, Object> entry : newValues.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (value == null) {
                    prefsMap.remove(key);
                } else {
                    prefsMap.put(key, value);
                }
            }
            savePrefs();
        }
    }
}
